﻿namespace KeRui.Common.IP
{
    using System;
    using System.Text.RegularExpressions;

    public class BlockIP
    {
        public static long CalcIP(string ip)
        {
            string[] strArray = ip.Split(new char[] { '.' });
            return ((((((Convert.ToInt64(strArray[0]) * 0x100L) * 0x100L) * 0x100L) + ((Convert.ToInt64(strArray[1]) * 0x100L) * 0x100L)) + (Convert.ToInt64(strArray[2]) * 0x100L)) + Convert.ToInt64(strArray[3]));
        }

        public static RestrictionIPResult GenerateIPList(string ip)
        {
            string[] strArray;
            RestrictionIPResult result = new RestrictionIPResult(false, 0L, 0L);
            if (!ip.Contains("-") && !ip.Contains("*"))
            {
                if (IsIP(ip))
                {
                    result.IsChecked = true;
                    result.StartIP = CalcIP(ip);
                    result.EndIP = CalcIP(ip);
                }
                return result;
            }
            if (ip.Contains("-") && !ip.Contains("*"))
            {
                strArray = ip.Split(new char[] { '-' });
                if (IsIP(strArray[0]) && IsIP(strArray[1]))
                {
                    result.IsChecked = true;
                    if (CalcIP(strArray[0]) < CalcIP(strArray[1]))
                    {
                        result.StartIP = CalcIP(strArray[0]);
                        result.EndIP = CalcIP(strArray[1]);
                        return result;
                    }
                    result.StartIP = CalcIP(strArray[1]);
                    result.EndIP = CalcIP(strArray[0]);
                }
                return result;
            }
            if (ip.Contains("*"))
            {
                strArray = new string[] { ip.Replace("*", "0"), ip.Replace("*", "254") };
                if (!(IsIP(strArray[0]) && IsIP(strArray[1])))
                {
                    return result;
                }
                result.IsChecked = true;
                if (CalcIP(strArray[0]) < CalcIP(strArray[1]))
                {
                    result.StartIP = CalcIP(strArray[0]);
                    result.EndIP = CalcIP(strArray[1]);
                    return result;
                }
                result.StartIP = CalcIP(strArray[1]);
                result.EndIP = CalcIP(strArray[0]);
            }
            return result;
        }

        private static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}

